//
//  HomePageDetialVC.swift
//  仿苹果首页动画
//
//  Created by slience on 2019/8/19.
//  Copyright © 2019 shehuiren. All rights reserved.
//

import UIKit

let SCREEN_WIDTH = UIScreen.main.bounds.size.width
let SCREEN_HEIGHT = UIScreen.main.bounds.size.height

class HomePageDetialVC: UIViewController {
    
    var bgImage : UIImage?
    var headImageView : UIImageView?
    var imageName : String?
    var selectIndexPath : IndexPath?
    var  isHorizontal : Bool?
    var startPointY : CGFloat?
    var startPointX : CGFloat?
    var scale : CGFloat?
    var headBg : UIView? //tabeleView header 的背景
//    @IBOutlet weak var myTableView : UITableView!
    
        lazy var myTableView : UITableView = {
    
            let tab = UITableView(frame: UIScreen.main.bounds, style: .plain)
            tab.delegate = self
            tab.dataSource = self
            tab.backgroundColor = UIColor.purple
    
            return tab
        }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        myTableView.estimatedRowHeight = 0
        
        myTableView.estimatedSectionHeaderHeight = 0
        
        myTableView.estimatedSectionFooterHeight = 0
        
        scale = 1
        let bgImgV = UIImageView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        
        view.addSubview(bgImgV)
        
        view.backgroundColor = UIColor.red
        
        bgImgV.image = bgImage
        
        let effect = UIBlurEffect(style: .light)
        
        let effectView = UIVisualEffectView(effect: effect)
        
        effectView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        
        view.addSubview(effectView)
        
        view.addSubview(myTableView)
        self.navigationController?.delegate = self
        myTableView.tableHeaderView = tableViewHeaderView()
        
        let pan = UIPanGestureRecognizer(target: self, action: #selector(pan(panGesture:)))
        pan.delegate = self
        myTableView.addGestureRecognizer(pan)
        
    }
    
    override var prefersStatusBarHidden: Bool{
        
        return true
    }
    
    @objc func pan(panGesture : UIPanGestureRecognizer){
        
        switch panGesture.state {
        case .began:
            let currentPoint = panGesture.location(in: myTableView)
            startPointY = currentPoint.y
            startPointX = currentPoint.x
            if startPointX! > CGFloat(50.0){
                isHorizontal = false
            }else{
                isHorizontal = true
            }
            break
        case .changed :
            
            let currentPoint = panGesture.location(in: myTableView)
            
            if  isHorizontal == true{
                
                if (currentPoint.x - startPointX!) > (currentPoint.y - startPointY!){
                    
                    scale = (SCREEN_WIDTH-(currentPoint.x-startPointX!))/SCREEN_WIDTH
                }else{
                    
                    scale = (SCREEN_HEIGHT-(currentPoint.y-startPointY!))/SCREEN_HEIGHT
                }
            }else{
                scale = (SCREEN_HEIGHT-(currentPoint.y-startPointY!))/SCREEN_HEIGHT
            }
            
            if scale! > CGFloat(1.0) {
                
                scale = 1.0
            }else if scale! <= CGFloat(0.8) {
                scale = 0.8
                
                DispatchQueue.main.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: UInt64(0.03))) {
                    
                    self.navigationController?.popViewController(animated: true)
                }
                
                
                //
                
            }
            
            // 初始开始 根据scale的变小 myTableView.contentOffset.y 也越来越小
            if myTableView.contentOffset.y <= 0 {
                
                myTableView.transform = CGAffineTransform.init(scaleX: scale!, y: scale!)
                
                myTableView.layer.masksToBounds = true
                myTableView.layer.cornerRadius = 15/20*(1-scale!)*100//15 * (1-scale!)*5*1.08
                
            }
            
            // 手指滑动的时候 停止列表 滚动 防止tableview上的内容滚动
            if scale! < 0.99{
                myTableView.isScrollEnabled = false
            } else {
                myTableView.isScrollEnabled = true
            }
            
            break
            
        case .ended:
            
            scale = 1.0
            myTableView.isScrollEnabled = true
            
            if scale! > 0.8 {
                
                UIView.animate(withDuration: 0.2) {[weak self]in
                    
                    self?.myTableView.layer.cornerRadius = 0
                    
                    self?.myTableView.transform = CGAffineTransform.init(scaleX: 1.0, y: 1.0)
                    
                }
            }
            
            break
        default:
            
            
            
            break
            
        }
    }
    
    
    func tableViewHeaderView() -> UIView{
        
        headBg = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_WIDTH*1.5))
        
        headBg?.backgroundColor = UIColor.blue
        
        headImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_WIDTH*1.5))
        headImageView?.image = UIImage(named: self.imageName!)
        headImageView?.contentMode = .scaleToFill
        headBg?.addSubview(headImageView!)

        
       
        //        headerView.addSubview(titleLabel!)
        //        headerView.addSubview(titleTwoLabel!)
        
        return headBg!
        
        
    }
   
    

}

extension HomePageDetialVC : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "id")
        
        if cell == nil{
            
            cell = UITableViewCell(style: .default, reuseIdentifier: "id")
            
            cell?.selectionStyle = .none
            
            cell?.backgroundColor  = UIColor.clear
            
            cell?.contentView.backgroundColor = UIColor.clear
            
            
        }
        
        let contentL = UILabel(frame: CGRect(x: 15, y: 0, width: SCREEN_WIDTH - 30, height: 20))
        
        contentL.numberOfLines = 0
        
        contentL.text = "黑天鹅 \n隶属于北京黑天鹅餐饮管理有限公司"
        
        cell?.contentView.addSubview(contentL)
        
        return cell!
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if scrollView.contentOffset.y <= 0 {
            
            scrollView.contentOffset.y = 0
//            let rectQ = scrollView.contentOffset
//
//             headImageView?.frame.origin = rectQ
//            var rectQ = self.headImageView?.frame
//            rectQ?.origin.y = scrollView.contentOffset.y
//            self.headImageView?.frame = rectQ!
        
//            var rectH = self.headBg?.frame
//            rectH?.size.height += scrollView.contentOffset.y
//            self.headBg?.frame = rectH!
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 20
    }
    
    
}

extension HomePageDetialVC : UINavigationControllerDelegate,UIViewControllerAnimatedTransitioning,UIGestureRecognizerDelegate{
    
    func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?{
    
    
        return self
    }
    
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool{
        
        if let onView  = otherGestureRecognizer.view, onView.isKind(of: UITableView.self){
            
            return true
        }
        
        return false
    }
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        
        return 1.0
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        let fromVC = transitionContext.viewController(forKey: .from) as! HomePageDetialVC
        
        let toVC = transitionContext.viewController(forKey: .to) as! HomePageVC
        
        let fromView = headImageView
        
        let containerView = transitionContext.containerView
        
        var  cell : HomePageCell?
        
        if let index = selectIndexPath{
            
            cell = toVC.myTableView.cellForRow(at: index) as? HomePageCell
        }
        let toView = cell?.header
        
        //截屏
        let snapShotView = fromView?.snapshotView(afterScreenUpdates: false)
        
        snapShotView?.layer.masksToBounds = true
        snapShotView?.layer.cornerRadius = 15
        
        snapShotView?.frame  = containerView.convert(fromView!.frame, from: fromView?.superview)
        
         containerView.insertSubview(toVC.view, belowSubview: fromVC.view)
        
        containerView.addSubview(snapShotView!)
        
        toView?.isHidden = true
        fromView?.isHidden = true

        
        UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: .curveEaseIn, animations: {
            
            containerView.layoutIfNeeded()
            fromVC.view.alpha = 0.0
            snapShotView?.layer.cornerRadius = 15
            self.myTableView.frame = CGRect(x:  self.myTableView.frame.origin.x, y:  self.myTableView.frame.origin.y, width:  self.myTableView.frame.size.width, height: SCREEN_WIDTH*1.5*0.8)
            self.myTableView.layer.cornerRadius = 15
            snapShotView?.frame = containerView.convert(toView!.frame, from: toView?.superview)
            
        }) { (finish) in
            
            fromView?.isHidden = true
            snapShotView?.removeFromSuperview()
            toView?.isHidden = false
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
        
        

    }
    
    
    
}
